#!/usr/bin/env bash

# The script is created for starting a riscv64 qemu virtual machine with specific parameters.

RESTORE=$(echo -en '\001\033[0m\002')
YELLOW=$(echo -en '\001\033[00;33m\002')

## Configuration
vcpu=8
memory=8
memory_append=`expr $memory \* 1024`
drive="test.qcow2"
fw1="RISCV_VIRT_CODE.fd "
fw2="RISCV_VIRT_VARS.fd"
ssh_port=12055
cdrom="openEuler-riscv64.iso"

cmd="/usr/bin/qemu-system-riscv64 \
  -nographic -machine virt,pflash0=pflash0,pflash1=pflash1,acpi=off \
  -smp $vcpu -m ${memory}G \
  -display sdl \
  -audiodev pa,id=snd0 \
  -blockdev node-name=pflash0,driver=file,read-only=on,filename=$fw1 \
  -blockdev node-name=pflash1,driver=file,filename=$fw2 \
  -drive file=$drive,format=qcow2,id=hd0 \
  -object rng-random,filename=/dev/urandom,id=rng0 \
  -object memory-backend-ram,size=4G,id=ram1 \
  -numa node,memdev=ram1 \
  -object memory-backend-ram,size=4G,id=ram2 \
  -numa node,memdev=ram2 \
  -device virtio-vga \
  -device virtio-rng-device,rng=rng0 \
  -device virtio-scsi-pci \
  -device scsi-cd,drive=cdrom_drv,bootindex=2 \
  -drive file=$cdrom,if=none,id=cdrom_drv,format=raw,media=cdrom \
  -device virtio-blk-device,drive=hd0,bootindex=1 \
  -device virtio-net-device,netdev=usernet \
  -netdev user,id=usernet,hostfwd=tcp::$ssh_port-:22 \
  -device qemu-xhci -usb -device usb-kbd -device usb-tablet -device usb-audio,audiodev=snd0"

echo ${YELLOW}:: Starting VM...${RESTORE}
echo ${YELLOW}:: Using following configuration${RESTORE}
echo ""
echo ${YELLOW}vCPU Cores: "$vcpu"${RESTORE}
echo ${YELLOW}Memory: "$memory"G${RESTORE}
echo ${YELLOW}Disk: "$drive"${RESTORE}
echo ${YELLOW}SSH Port: "$ssh_port"${RESTORE}
echo ""
echo ${YELLOW}:: NOTE: Make sure ONLY ONE .qcow2 file is${RESTORE}
echo ${YELLOW}in the current directory${RESTORE}
echo ""
echo ${YELLOW}:: Tip: Try setting DNS manually if QEMU user network doesn\'t work well. ${RESTORE}
echo ${YELLOW}:: HOWTO -\> https://serverfault.com/a/810639 ${RESTORE}
echo ""
echo ${YELLOW}:: Tip: If \'ping\' reports permission error, try reinstalling \'iputils\'. ${RESTORE}
echo ${YELLOW}:: HOWTO -\> \'sudo dnf reinstall iputils\' ${RESTORE}
echo ""

sleep 2

eval $cmd

